#!/usr/bin/env python

import XenAPI
import XenAPIPlugin
import sys
import base64
import subprocess
path = "/opt/tpm/"
#Usage: ./aikrespond [-p password] aikblobfile challengefile outresponsefile
prg  =  path + "aikrespond"
cfile = path + "challange"
aikblob = path + "aiktpmblob"
outfile = path + "response"

def doexec(args, inputtext=None):
    """Execute a subprocess, then return its return code, stdout and stderr"""
    proc = subprocess.Popen(args,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
    (stdout,stderr) = proc.communicate(inputtext)
    rc = proc.returncode
    return (rc,stdout,stderr)

def call_exec():
    (rc,stdout,stderr) = doexec([prg, aikblob, cfile, outfile])
    return rc



def main(session, args):
    try:
        challange =  args['challange']
    	f = open(cfile,"w")
        f.write(base64.b64decode(challange))
        f.close()
        rc = call_exec()
        f = open(outfile,"r")
        rc = f.read()
        f.close()
        return rc
    except :
        raise

if __name__ == "__main__":
    XenAPIPlugin.dispatch({"main":main})
    #main(None,{"challange":cfile})
